import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Select, Button, Table, message, TreeSelect, Modal } from "antd";
import { EditOutlined, SearchOutlined } from "@ant-design/icons";
import { text_check, post_axios } from "../../utils";

export default function AccountSplitSet(props) {
  const { t } = useTranslation();
  const [tableHeight, setTableHeight] = useState(0);
  const { actions, setSpinning } = props;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  const [page, setPage] = useState(1);
  const [rows, setRows] = useState(20);
  const [total, setTotal] = useState(0);
  const [tableList, setTableList] = useState([]);

  const [com_ids_par, setCom_ids_par] = useState([]);

  const getData = async (newPage, newRows) => {
    let upMsg = {
      page: newPage ? newPage : page,
      rows: newRows ? newRows : rows,
      company_id: local_company_object.id,
      company: local_company_object.company,
      com_ids_par: JSON.parse(JSON.stringify(com_ids_par)),
    };
    setSpinning(true);
    let res = await post_axios("account_split_set", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setTableList(res.data_rows.rows);
    setTotal(res.data_rows.total);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("market.project"),
      dataIndex: "project",
      align: "center",
    },
    {
      title: t("market.point"),
      dataIndex: "point",
      align: "center",
    },
    {
      title: t("assets.strategy_name"),
      dataIndex: "plan_name",
      align: "center",
    },
  ];

  // 分页器
  const pageOnChange = async (page, pageSize) => {
    setPage(page);
    setRows(pageSize);
    initData(page, pageSize);
  };

  // 用户数据行点击
  const [clickRowKey, setClickRowKey] = useState([]);

  const tableRowClick = (row) => {
    const point_id = row.point_id;
    const idx = clickRowKey.indexOf(point_id);
    if (idx > -1) {
      const clickAvm = clickRowKey.filter((item) => item !== point_id);
      setClickRowKey(clickAvm);
    } else {
      setClickRowKey([...clickRowKey, point_id]);
    }
  };

  const search_data = () => {
    setPage(1);
    initData(1);
  };

  const initData = (page, rows) => {
    setClickRowKey([]);
    getData(page, rows);
  };

  // 分成配置
  const [edit_account_split_show, setEdit_account_split_show] = useState(false);
  const [edit_plan_id, setEdit_plan_id] = useState("");
  const account_split_set = async () => {
    if (clickRowKey.length === 0) {
      message.warning({
        content: t("assets.select_at_least_one_device"),
      });
      return;
    }
    setEdit_account_split_show(true);
  };
  const edit_avm_account_split_confirm = async () => {
    let upMsg = {
      plan_id: edit_plan_id,
      point_ids_par: clickRowKey,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    setSpinning(true)
    let res = await post_axios("account_split_set", "m_modify", upMsg);
    setSpinning(false)
    if (!res) return;
    setEdit_account_split_show(false);
    search_data();
  };

  // 获取组织列表
  const [com_list, setCom_list] = useState([]);
  const get_com_data = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_com_id",
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    setCom_list(res.data_rows.rows);
  };

  // 编辑设备的策略查询
  const [edit_plan_page, setEdit_plan_page] = useState(1);
  const [edit_plan_list, setEdit_plan_list] = useState([]);
  const get_plan_data = async (newPage) => {
    let upMsg = {
      page: newPage ? newPage : edit_plan_page,
      rows: 20,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let res = await post_axios("account_split_plan", "m_query", upMsg);
    if (!res) return;
    const receiveRows = res.data_rows.rows;
    setEdit_plan_list([...edit_plan_list, ...receiveRows]);
  };
  // 商户筛选框-分页
  const edit_plan_next_page = () => {
    setEdit_plan_page(edit_plan_page + 1);
    get_plan_data(edit_plan_page + 1);
  };

  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("account_split_set")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 70;
      setTableHeight(tableHeight);
    });
    if (user_grade < 70) {
      get_com_data();
    }
    get_plan_data();
  }, []);
  return (
    <>
      <div className="account_split_set modules">
        <div className="screen_ipt">
          {/* 组织 */}
          {user_grade < 70 ? (
            <div className="ipt_box ipt_box_long">
              <div className="ipt_box_title">{t("market.organization")}</div>
              <TreeSelect
                value={com_ids_par}
                treeData={com_list}
                allowClear={true}
                size="small"
                multiple
                treeCheckStrictly={true}
                fieldNames={{
                  label: "com",
                  value: "com_id",
                  children: "children",
                }}
                placeholder=" "
                treeCheckable={true}
                onChange={(newValue) => setCom_ids_par(newValue)}
              />
            </div>
          ) : (
            ""
          )}
        </div>
        <div className="screen_btn">
          <div className="btn_box">
            {/* 修改 */}
            {menu_action.indexOf("m_modify") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<EditOutlined style={{ color: "#1677FF" }} />}
                onClick={account_split_set}
              >
                {text_check(user_power_lang["m_modify"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div
            className="page-table"
            style={{
              width: "100vw",
            }}
          >
            <Table
              dataSource={tableList}
              size="small"
              bordered
              columns={columns}
              rowKey="point_id"
              virtual
              scroll={{
                y: tableHeight,
              }}
              onRow={(record) => {
                return {
                  onClick: () => tableRowClick(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (clickRowKey.indexOf(record.point_id) > -1) {
                  return "row_clicked_style";
                }
              }}
              rowHoverable={false}
              pagination={{
                defaultCurrent: page,
                defaultPageSize: rows,
                size: "small",
                current: page,
                total: total,
                responsive: true,
                showTotal: (total) =>
                  text_check({
                    msg_cn: `共 ${total} 条`,
                    msg_en: `Total ${total} items`,
                  }),
                onChange: pageOnChange,
              }}
            />
          </div>
        </div>
      </div>
      {/* 添加设备 */}
      <Modal
        title={t("assets.split_configuration")}
        open={edit_account_split_show}
        onOk={edit_avm_account_split_confirm}
        onCancel={() => setEdit_account_split_show(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">{t("assets.partition_strategy")}</div>
          <Select
            placeholder=" "
            allowClear={true}
            value={edit_plan_id}
            options={edit_plan_list}
            showSearch
            fieldNames={{
              label: "plan_name",
              value: "plan_id",
            }}
            onChange={(value) => setEdit_plan_id(value)}
            onPopupScroll={(event) => {
              if (edit_plan_list.length < edit_plan_page * 20) {
                console.log("没有更多数据了");
                return;
              }
              const target = event.target;
              const residueHeight =
                target.scrollHeight - target.scrollTop - target.clientHeight;
              if (residueHeight <= 50) {
                edit_plan_next_page();
              }
            }}
            optionFilterProp="plan_name"
          ></Select>
        </div>
      </Modal>
    </>
  );
}
